package com.mfrs.demos;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.cily.utils.base.HttpUtils;
import com.mfrs.ActionResult;
import com.mfrs.FaceData;
import com.mfrs.HttpU;
import com.mfrs.IFRSMobileService;
import com.mfrs.adapter.LvRecordAdapter;
import com.mfrs.adapter.RecordBean;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import hk.cic.demointegrationapp.R;

public class TestActivity extends ActionBarActivity {
	private final String TAG = this.getClass().getSimpleName();
	private ImageView img_avatar, img_edit;
	private TextView tv_name, tv_id, tv_address, tv_gps;
	private ListView lv_id;
	
	private LvRecordAdapter adapter;
	private List<RecordBean> list_record;

	private final String imageNameForFace = "image_face_0.jpg";
	private final String imageNameForCheck = "image_face_9.jpg";
	private final int REQUEST_CODE_FACE_GET = 101;
	private final int REQUEST_CODE_FACE_CHECK_IN = 102;
	private final int REQUEST_CODE_FACE_CHECK_OUT = 103;
	
	private final int REQUEST_CODE_USER_EDIT = 110;

	private com.mfrs.FaceData faceData1;
	private com.mfrs.FaceData faceData2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_test);

		if (!isSvcConnected) {
			showProgressDialog("正在初始化，请耐心等待...");
			isSvcConnected = connectToFrsMobileService();
			Log.i(TAG, "onCreate Connect to FRS Mobile Service: " + String.valueOf(isSvcConnected));
		}

		initUI();
	}

	private void initUI() {
		findViewById(R.id.img_titleBar_left).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});

		img_avatar = (ImageView) findViewById(R.id.img_avatar);
		img_avatar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isSvcConnected) {
					if (!connectToFrsMobileService()) {
						showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
						return;
					}
				}
				if (!isInit) {
					showAlertDialog(R.string.err_mfrs_not_init, R.string.title_err);
					return;
				}

				dialogForPhoto(REQUEST_CODE_FACE_GET);
			}
		});
		tv_name = (TextView) findViewById(R.id.tv_name);
		
		img_edit = (ImageView) findViewById(R.id.img_edit);
		img_edit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				EditAc.start(TestActivity.this, REQUEST_CODE_USER_EDIT, tv_name.getText().toString().trim());
			}
		});

		
		tv_id = (TextView) findViewById(R.id.tv_ID);
		tv_address = (TextView) findViewById(R.id.tv_address);
		tv_gps = (TextView) findViewById(R.id.tv_GPS);

		findViewById(R.id.tv_exit).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		findViewById(R.id.tv_out).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!checkConn()){
					showToast("未完成初始化...");
					return;
				}
				if(faceData1 == null){
					showToast("请先录入标准人脸");
					return;
				}
				
				dialogForPhoto(REQUEST_CODE_FACE_CHECK_OUT);
			}
		});

		findViewById(R.id.tv_in).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!checkConn()){
					showToast("未完成初始化...");
					return;
				}
				if(faceData1 == null){
					showToast("请先录入标准人脸");
					return;
				}
				
				dialogForPhoto(REQUEST_CODE_FACE_CHECK_IN);
			}
		});

		list_record = new ArrayList<RecordBean>();
		lv_id = (ListView) findViewById(R.id.lv_id);
		adapter = new LvRecordAdapter(list_record);
		lv_id.setAdapter(adapter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
		if (isSvcConnected) {
			Log.i(TAG, "unbindservice");
			this.unbindService(mServiceConnection);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			showToast("已取消");
			return;
		}
			if (requestCode == REQUEST_CODE_FACE_GET) {
				handleImage(REQUEST_CODE_FACE_GET, false);
			} else if (requestCode == REQUEST_CODE_FACE_CHECK_IN) {
				handleImage(REQUEST_CODE_FACE_CHECK_IN, false);
			} else if (requestCode == REQUEST_CODE_FACE_CHECK_OUT) {
				handleImage(REQUEST_CODE_FACE_CHECK_OUT, false);
			}else if(requestCode == REQUEST_CODE_USER_EDIT){
				tv_name.setText(data.getStringExtra(EditAc.USER_NAME) + "");
			}
		
	}

	private boolean isInit = false;
	private IFRSMobileService frsMobileService;
	private boolean isSvcConnected = false;

	private boolean connectToFrsMobileService() {
		isInit = false;
		Intent serviceIntent = new Intent();
		serviceIntent.setClassName("com.mfrs", "com.mfrs.FRSMobileService");
		isSvcConnected = bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
		Log.i(TAG, "connectToFrsMobileService: " + String.valueOf(isSvcConnected));

		return isSvcConnected;
	}

	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			frsMobileService = IFRSMobileService.Stub.asInterface(service);
			
//			showAlertDialog(R.string.msg_mfrs_init_ok, R.string.str_init);
			showToast(getString(R.string.msg_mfrs_init_ok));
			Uri imageUri = Uri
					.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
			if(imageUri == null){
				hideProDia();
				return;
			}
			
			File f = new File(imageUri.getPath());
			if(f == null || !f.exists()){
				hideProDia();
			}else{
				handleImage(REQUEST_CODE_FACE_GET, true);
			}

			isInit = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.e(TAG, "Service Disconnected.");
		}
	};
	
	private void showToast(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private boolean checkConn() {
		if (!isSvcConnected) {
			if (!connectToFrsMobileService()) {
				showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
				return false;
			}
		}
		if (!isInit) {
			showAlertDialog(R.string.err_mfrs_not_init, R.string.title_err);
			return false;
		}
		return true;
	}

	private void match(int type) {
		if (!isSvcConnected) {
			if (!connectToFrsMobileService()) {
				showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
				return;
			}
		}

		if (!isInit) {
			showAlertDialog(R.string.err_initialization_in_progress, R.string.title_err);
			return;
		}

//		TextView tv = (TextView) findViewById(R.id.labelScoreResult);

		if (faceData1 != null && faceData2 != null) {

			Log.i(TAG, "try match");
			float[] score = new float[1];
			score[0] = -1.0f;

			try {
				long time = System.nanoTime();
				ActionResult ar = frsMobileService.faceMatching(faceData1.getFeatureData(), faceData2.getFeatureData(),
						score);
				time = System.nanoTime() - time;
				// tvTime.setText("faceMatching used time: " +
				// String.valueOf(time));

				if (ar.getCode() == ActionResult.CODE_Success) {
					Log.i(TAG, "score " + String.valueOf(score[0]));
//					tv.setText(String.valueOf(score[0]));
//					((TextView) findViewById(R.id.textViewError)).setText("");
					showMatchResult("比对分数：" + String.valueOf(score[0]) 
					+ "\n比对结果：" + (score[0] >= 0.5 ? "通过" : "不通过"), type, score[0] >= 0.5);
					
				} else {
					showAlertDialog(ar);
//					tv.setText("-");
					Log.e(TAG, "Err: " + String.valueOf(ar.getCode()));
					Log.e(TAG, "Err: " + ar.getRemark());
//					((TextView) findViewById(R.id.textViewError))
//							.setText(String.valueOf(ar.getCode()) + " " + ar.getRemark());
				}

			} catch (RemoteException e) {

				Log.e(TAG, e.getMessage());
				showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
				isSvcConnected = false;
				e.printStackTrace();
			}
		} else {
//			tv.setText("-");
			Log.e(TAG, "Either FaceData1 or FaceData2 is null");
			if(faceData1 == null){
				showToast("请录入标准人脸");
			}else{
				showToast("请录入待比对的人脸");
			}
		}
	}

	private void dialogForPhoto(final int type) {
		new AlertDialog.Builder(this).setTitle(R.string.str_title_photo)
				.setMessage(R.string.str_land_screen_for_take_picture)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

						toCamera(type);
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
	}

	private void showAlertDialog(int message, int title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setTitle(title);
		AlertDialog dialog = builder.create();
		dialog.show();
	}



	@SuppressLint("DefaultLocale")
	private void handleImage(int imageRequest, boolean loadFaceFromSD) {
		hideProDia();
		Uri imageUri = null;
		if (imageRequest == REQUEST_CODE_FACE_GET) {
			imageUri = Uri
					.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
			faceData1 = null;
		} else {
			imageUri = Uri
					.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForCheck));
			faceData2 = null;
		}

		Bitmap bMap, resizedBitmap, canvasBitmap = null;
		try {
			if (imageUri == null) {
				if(loadFaceFromSD){
					showToast("请录入标准人脸");
				}else{
					showToast("人脸图片不存在");
				}
//				showAlertDialog(R.string.err, R.string.title_err);
				Log.e(TAG, "ImageUri is null.");
				return;
			}

			File f = new File(imageUri.getPath());
			if (!f.exists()) {
				showAlertDialog("File does not exist! " + f.toString(), getResources().getString(R.string.title_err));
				Log.e(TAG, "File does not exist!" + f.toString());
				return;
			}

			byte[] image = FileUtils.readFileToByteArray(f);
			int imageSize = image.length / 1024;
			Log.i(TAG, String.format("Image size before resizing: %d", imageSize));

			bMap = BitmapFactory.decodeByteArray(image, 0, image.length);

			if (bMap == null) {
				showAlertDialog(R.string.err_imagefile, R.string.title_err);
				Log.e(TAG, "File does not exist!" + f.toString());
				return;
			}

			Log.i(TAG, String.format("Current width * height: %d x %d ", bMap.getWidth(), bMap.getHeight()));

			Dimension imgDimension = new Dimension(bMap.getWidth(), bMap.getHeight());
			Dimension boundaryHorizontalDimension = new Dimension(MainActivity.MAX_WIDTH, MainActivity.MAX_HEIGHT);
			Dimension boundaryVerticalDimension = new Dimension(MainActivity.MAX_HEIGHT, MainActivity.MAX_WIDTH);
			Log.i(TAG, String.format("Img Resolution before resizing: %d x %d", imgDimension.getWidth(),
					imgDimension.getHeight()));

			Dimension newDimension = imgDimension;
			Boolean resized = false;
			resizedBitmap = bMap;

			if (bMap.getWidth() > bMap.getHeight()) {
				if (bMap.getWidth() > MainActivity.MAX_WIDTH || bMap.getHeight() > MainActivity.MAX_HEIGHT) {
					Log.i(TAG, String.format("Img Boundary: %d x %d", boundaryHorizontalDimension.getWidth(),
							boundaryHorizontalDimension.getHeight()));
					newDimension = getScaledDimension(newDimension, boundaryHorizontalDimension);
					resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),
							false);
					resized = true;
				}
			} else {
				Log.i(TAG, "width < height");
				if (bMap.getWidth() > MainActivity.MAX_HEIGHT || bMap.getHeight() > MainActivity.MAX_WIDTH) {
					Log.i(TAG, String.format("Img Boundary: %d x %d", boundaryVerticalDimension.getWidth(),
							boundaryVerticalDimension.getHeight()));
					newDimension = getScaledDimension(newDimension, boundaryVerticalDimension);
					resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),
							false);
					resized = true;
				}
			}

			Log.i(TAG, String.format("Img Resolution after resizing: %d x %d", resizedBitmap.getWidth(),
					resizedBitmap.getHeight()));

			ArrayList<FaceData> fdList = new ArrayList<FaceData>();
			ActionResult ar = null;

			if (resized) {
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
				byte[] resizedImageByte = stream.toByteArray();
				int size = resizedImageByte.length / 1024;
				Log.i(TAG, "Size after resizing: " + resizedImageByte.length / 1024 + "KB");

				if (size < 800) {
					// imgView.setImageBitmap(resizedBitmap);
//					img_avatar.setImageBitmap(resizedBitmap);
					long time = System.nanoTime();
					ar = frsMobileService.faceDataDetection(resizedImageByte, fdList);
					time = System.nanoTime() - time;
					// tvTime.setText("faceDataDetection used time:
					// " + String.valueOf(time));
				} else {
					showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
					Log.e(TAG, "Please keep image less than 800KB after compression");
				}

				resizedImageByte = null;
			} else {
				try {
					if (image.length / 1024 < 1000) {
						// imgView.setImageBitmap(resizedBitmap);
//						img_avatar.setImageBitmap(resizedBitmap);
						Log.i(TAG, "Before faceDataDetection");
						long time = System.nanoTime();
						ar = frsMobileService.faceDataDetection(image, fdList);
						time = System.nanoTime() - time;
						// tvTime.setText("faceDataDetection used
						// time: " + String.valueOf(time));
						Log.i(TAG, "After faceDataDetection");
					} else {
						showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
						Log.e(TAG, "Image Size exceeds 1MB after compression");
					}

				} catch (Exception e) {
					Log.e(TAG, "Error in FaceDataDetection");
				}

			}

			if (ar == null) {
				showAlertDialog(R.string.err, R.string.title_err);
				Log.e(TAG, "Action Result is null");
				return;
			}

			if (ar.getCode() != ActionResult.CODE_Success) {
//				showAlertDialog(ar);

				if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
					// isFaceFoundTextView.setText("Face Found:
					// No");
					// faceQualityScoreTextView.setText("Face
					// Quality: -");
					// errTextView.setText("Face Not Found");
					showFaceQualityDialog(RESULT_ERROR, imageRequest, "未检测到人脸");
				} else {
					// isFaceFoundTextView.setText("Face Found:
					// Err");
					// faceQualityScoreTextView.setText("Face
					// Quality: Err");
					// errTextView.setText(String.valueOf(ar.getCode())
					// + ": " + ar.getRemark());
					showFaceQualityDialog(RESULT_ERROR, imageRequest, "人脸质量不佳");
				}
				return;
			}

			if (fdList.size() > 0) {
				// highlight the head and eyes positions
				Log.i(TAG, String.format("Feature Data List Size: %d", fdList.size()));

				Bitmap copiedImage = resizedBitmap.copy(Bitmap.Config.ARGB_8888, true);
				Canvas canvas = new Canvas(copiedImage);

				try {
					canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
							Bitmap.Config.ARGB_8888);
				} catch (OutOfMemoryError e) {
					while (canvasBitmap == null) {
						System.gc();
						System.runFinalization();
						Log.i(TAG, "Draw On Image: Create Bitmap out Of Memory Error.\nCreate again now.");
						canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
								Bitmap.Config.ARGB_8888);
					}
				}

				for (int i = 0; i < fdList.size(); i++) {
					int[] headArray = fdList.get(i).getHead();
					int[] leftEyeArray = fdList.get(i).getLeftEye();
					int[] rightEyeArray = fdList.get(i).getRightEye();

					if (headArray != null && leftEyeArray != null && rightEyeArray != null) {
						try {
							String rectString = String.format("New head in Main: left %d, top %d, right %d, bottom %d",
									headArray[0], headArray[1], headArray[2], headArray[3]);
							Log.i(TAG, rectString);

							Paint rectpaint = new Paint();
							rectpaint.setStyle(Paint.Style.STROKE);
							rectpaint.setColor(Color.GREEN);
							rectpaint.setStrokeWidth(7);
							float leftx = headArray[0];
							float topy = headArray[1];
							float rightx = headArray[2];
							float bottomy = headArray[3];

							Paint cirpaint = new Paint();
							cirpaint.setStyle(Paint.Style.STROKE);
							cirpaint.setColor(Color.GREEN);
							cirpaint.setStrokeWidth(5);

							if (i == 0) {
								rectpaint.setColor(Color.CYAN);

								cirpaint.setColor(Color.CYAN);
							}

							canvas.drawRect(leftx, topy, rightx, bottomy, rectpaint);
							canvas.drawCircle(leftEyeArray[0], leftEyeArray[1], 10, cirpaint);
							canvas.drawCircle(rightEyeArray[0], rightEyeArray[1], 10, cirpaint);

						} catch (Exception e) {
							Log.e(TAG, "Exception encountered in drawing Image");
							showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
							// imgView.setImageBitmap(resizedBitmap);
//							img_avatar.setImageBitmap(resizedBitmap);
						}

					} else {
						Log.e(TAG, "HeadArray or EyeArray is null");
						showAlertDialog(R.string.error_headeye_notok, R.string.title_err);
						// imgView.setImageBitmap(resizedBitmap);
//						img_avatar.setImageBitmap(resizedBitmap);
					}
				}

				// imgView.setImageBitmap(copiedImage);
				if(imageRequest == REQUEST_CODE_FACE_GET){
					img_avatar.setImageBitmap(copiedImage);
				}

			} else {
				Log.e(TAG, "Cannot find feature data");
			}

			if (fdList.size() > 0) {
				// isFaceFoundTextView.setText("Face Found:
				// Yes");
				// faceQualityScoreTextView.setText(
				// "Face Quality:" +
				// String.valueOf(fdList.get(0).getFaceQualityScore()));
				
				if(!loadFaceFromSD){
					showFaceQualityDialog(RESULT_SUCCESS, imageRequest, 
						"分数：" + fdList.get(0).getFaceQualityScore());
				}
				if (imageRequest == REQUEST_CODE_FACE_GET) {
					faceData1 = fdList.get(0);

					Log.i(TAG, "set faceData1");
				} else if (imageRequest == REQUEST_CODE_FACE_CHECK_IN || imageRequest == REQUEST_CODE_FACE_CHECK_OUT) {
					faceData2 = fdList.get(0);
					Log.i(TAG, "set faceData2");
				}
				// errTextView.setText("");
			}

			resizedBitmap = null;
			bMap = null;
			canvasBitmap = null;

		} catch (IOException e) {
			showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
			e.printStackTrace();
		} catch (RemoteException e) {
			showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
			isSvcConnected = false;
			e.printStackTrace();
		} catch (Exception e) {
			showAlertDialog(e.getMessage(), "ERROR");
			e.printStackTrace();
		}
	}
	
	private void showMatchResult(String msg, final int type, final boolean pass){
		new AlertDialog.Builder(this).setTitle("比对结果").setMessage(msg)
			.setNegativeButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					
					if(pass){
						if(list_record == null){
							list_record = new ArrayList<RecordBean>();
						}
						
						RecordBean b = getRecord(getDate(), tv_name.getText().toString().trim());
						if(b == null){
							b = new RecordBean();
							b.setDate(getDate());
							b.setUser(tv_name.getText().toString().trim());
							if(type == REQUEST_CODE_FACE_CHECK_IN){
								b.setInTime(getTime());
							}else if(type == REQUEST_CODE_FACE_CHECK_OUT){
								b.setOutTime(getTime());
							}
							list_record.add(b);
							adapter.notifyDataSetChanged();
						}else{
							if(type == REQUEST_CODE_FACE_CHECK_IN){
								b.setInTime(getTime());
							}else if(type == REQUEST_CODE_FACE_CHECK_OUT){
								b.setOutTime(getTime());
							}
							adapter.notifyDataSetChanged();
						}
					}
				}
			}).create().show();
	}
	
	private String getDate(){
		return milToStr(System.currentTimeMillis(), "yyyy-MM-dd");
	}
	
	private String getTime(){
		return milToStr(System.currentTimeMillis(), "HH:mm:ss");
	}
	
	private String milToStr(long time, String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try{
			return sdf.format(time);
		}catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private RecordBean getRecord(String date, String user){
		if(list_record == null){
			return null;
		}
		
		RecordBean r = null;
		
		for(RecordBean b : list_record){
			if(b.getDate().equals(date) && b.getUser().equals(user)){
				r = b;
				break;
			}
		}
		return r;
	}
	
	
	private final int RESULT_SUCCESS = 0, RESULT_ERROR = -1;
	private void showFaceQualityDialog(final int result, final int type, String msg){
		String ok = "确定";
		if(result == RESULT_SUCCESS){
			
		}else{
			ok = "重拍";
		}
		
		new AlertDialog.Builder(this).setTitle("人脸检测")
			.setMessage(msg)
			.setPositiveButton(ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					if(result == RESULT_SUCCESS){
						if(type == REQUEST_CODE_FACE_GET){
							
						}else if(type == REQUEST_CODE_FACE_CHECK_IN){
							match(REQUEST_CODE_FACE_CHECK_IN);
						}else if(type == REQUEST_CODE_FACE_CHECK_OUT){
							match(REQUEST_CODE_FACE_CHECK_OUT);
						}
					}else{
						toCamera(type);
					}
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create().show();
	}

	public Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
		int original_width = imgSize.width;
		int original_height = imgSize.height;
		int bound_width = boundary.width;
		int bound_height = boundary.height;
		int new_width = original_width;
		int new_height = original_height;

		// first check if we need to scale width
		if (original_width > bound_width) {
			// scale width to fit
			new_width = bound_width;
			// scale height to maintain aspect ratio
			new_height = (new_width * original_height) / original_width;
		}

		// then check if we need to scale even with the new height
		if (new_height > bound_height) {
			// scale height to fit instead
			new_height = bound_height;
			// scale width to maintain aspect ratio
			new_width = (new_height * original_width) / original_height;
		}

		return new Dimension(new_width, new_height);
	}

	private void showAlertDialog(String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setTitle(title);
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private void showAlertDialog(ActionResult ar) {
		String message = "";
		if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
//			message = "CODE_FaceNotFound: " + ar.getRemark();
			message = "未检测到人脸：" + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_FRSEngineError) {

//			message = "CODE_FRSEngineError: " + ar.getRemark();
			message = "FRS错误：" + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_ImageFormatNotSupport) {
//			message = "CODE_ImageFormatNotSupport: " + ar.getRemark();
			message = "图片格式不支持：" + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData1) {
			message = "CODE_InvalidFeatureData1: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData2) {
			message = "CODE_InvalidFeatureData2: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseExpired) {
//			message = "CODE_LicenseExpired: " + ar.getRemark();
			message = "License已过期：" + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseNotValid) {
//			message = "CODE_LicenseNotValid: " + ar.getRemark();
			message = "License验证未通过：" + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_UnknownError) {
//			message = "CODE_UnknownError: " + ar.getRemark();
			message = "未知异常：" + ar.getRemark();
		}
		showAlertDialog(message, getResources().getString(R.string.title_err));
	}

	private void toCamera(int requestCode) {
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		String fileName = null;
		if (requestCode == REQUEST_CODE_FACE_GET) {
			fileName = imageNameForFace;
		} else {
			fileName = imageNameForCheck;
		}

		Uri uriImage1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + fileName));
		cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uriImage1);
		startActivityForResult(cameraIntent, requestCode);
	}
	
	private ProgressDialog proDia;
	private void showProgressDialog(String msg){
		proDia = ProgressDialog.show(this, "提示", msg, false, true);
	}
	private void hideProDia(){
		if(proDia != null){
			proDia.dismiss();
		}
	}

	private class Dimension {
		private final int width;
		private final int height;

		public Dimension(int width, int height) {
			this.width = width;
			this.height = height;
		}

		public int getWidth() {
			return this.width;
		}

		public int getHeight() {
			return this.height;

		}
	}
}